package com.example.demo.database;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

@Component
public class DatabaseInitializer {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public DatabaseInitializer(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @PostConstruct
    public void init() {
        //createUsersTable();
        //insertInitialUsers();
        printAllUsers();
    }

    private void createUsersTable() {
        jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS users (" +
                "id BIGSERIAL PRIMARY KEY, " +
                "name VARCHAR(255) NOT NULL, " +
                "username VARCHAR(255) UNIQUE NOT NULL, " +
                "password VARCHAR(255) NOT NULL, " +
                "email VARCHAR(255) UNIQUE NOT NULL, " +
                "phone VARCHAR(255), " +
                "role VARCHAR(255) NOT NULL, " +
                "registration_date TIMESTAMPTZ NOT NULL DEFAULT NOW()" +
                ")");
    }

    private void insertInitialUsers() {
        jdbcTemplate.update("INSERT INTO users (name, username, password, role, email, phone, registration_date) VALUES (?, ?, ?, ?, ?, ?, NOW())",
                "Alice Smith", "alice123", "password123", "普通员工", "alice@example.com", "1234567890");
        jdbcTemplate.update("INSERT INTO users (name, username, password, role, email, phone, registration_date) VALUES (?, ?, ?, ?, ?, ?, NOW())",
                "Bob Johnson", "bob456", "password456", "管理员", "bob@example.com", "0987654321");
        jdbcTemplate.update("INSERT INTO users (name, username, password, role, email, phone, registration_date) VALUES (?, ?, ?, ?, ?, ?, NOW())",
                "Charlie Lee", "charlie789", "password789", "普通员工", "charlie@example.com", "1122334455");
    }

    private void printAllUsers() {
        List<Map<String, Object>> users = jdbcTemplate.queryForList("SELECT * FROM users");
        for (Map<String, Object> user : users) {
            System.out.println(user);
        }
    }
}
